package com.qiu.greened.utils

import android.view.MenuItem
import androidx.core.view.forEachIndexed
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.bottomnavigation.BottomNavigationView

class BnvVp2Mediator(
    private val bnv: BottomNavigationView,
    private val vp2: ViewPager2,
    private val config: ((BottomNavigationView,ViewPager2) -> Unit)? = null
) {
    private val map = mutableMapOf<MenuItem, Int>()

    init {
        //建立MenuItem的索引id映射
        bnv.menu.forEachIndexed { index, item ->
            map[item] = index
        }
    }

    fun attach() {
        //由于config是可空类型 所以必须用invoke执行
        config?.invoke(bnv,vp2)
        //监听viewPager的页面改变
        vp2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                //通过position参数 设置BottomNavigationView选中的Item
                bnv.selectedItemId = bnv.menu.getItem(position).itemId
            }
        })

        //监听BottomNavigationView的item点击
        bnv.setOnNavigationItemSelectedListener { menuItem ->
            vp2.currentItem =
                map[menuItem] ?: error("BottomNavigationView的Item${menuItem.itemId}没有对应的元素")
            true
        }
    }
}
